/*
 * Created on Sep 27, 2003
 * Local Projects Database
 * Copyright (c) 2003 by eRomania Gateway
 */
package ro.gateway.aida.struts.action;

import java.sql.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.actions.TilesAction;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.db.ActivityDB;
import ro.gateway.aida.usr.Arbiter;
import ro.gateway.aida.usr.Perms;
import ro.gateway.aida.usr.User;
import ro.gateway.aida.usr.UserUtils;
import ro.gateway.aida.usr.messaging.Alert;
import ro.gateway.aida.usr.messaging.AlertDB;
import ro.gateway.aida.usr.messaging.Approve;
import ro.gateway.aida.usr.messaging.ApproveDB;
import ro.gateway.aida.usr.messaging.Event;
import ro.gateway.aida.utils.BugTracker;
import ro.gateway.aida.utils.HttpUtils;
import ro.gateway.aida.utils.PageToken;
import ro.gateway.aida.utils.SortedList;
import ro.gateway.aida.utils.Utils;
import ro.xblue.translator.LanguageBean;
import ro.xblue.translator.TranslatorUtils;


/**
 * @author Mihai Postelnicu
 *
 * This action handles the web interaction for approvals
 * View,delete,approve,reject...
 */
public class ApproveAction extends TilesAction {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        ServletContext sc = getServlet().getServletContext();
        PersistenceToken token = PersistenceManager.tokenLookup(sc);

        try {
            Arbiter ar = Arbiter.getManager(token);
            long user_id = HttpUtils.getLong(request, "user_id", 0);
            long event_id = HttpUtils.getLong(request, "event_id", 0);
            long id = HttpUtils.getLong(request, "id", 0);
            String approve = request.getParameter("approve");
            String optionmade = request.getParameter("optionmade");
            String reason = request.getParameter("reason");
            String mode = request.getParameter("mode");
            String sshow = request.getParameter("show");
            String sort = request.getParameter("sort");
            HttpSession session = request.getSession();

            int feedback = HttpUtils.getInt(request, "feedback", 0);
            ApproveDB apdb = ApproveDB.getManager(token);
            AlertDB aldb = AlertDB.getManager(token);
            ActivityDB actdb = ActivityDB.getManager(token);

            //show my approvals
            User user = UserUtils.getLogged(request, response);

            if (user == null)
                return mapping.findForward("plslogin");

            LanguageBean lang_bean = TranslatorUtils.getCurrentLanguage(request,
                    sc);
            String lang = lang_bean.language;
            boolean blank = false;

            if (!ar.canDo(request, Perms.OBJECT_APPROVE)) {
                if (!"widget".equals(mode)) {
                    session.invalidate();

                    return mapping.findForward("norights");
                } else
                    blank = true;
            }

            if ((user_id != 0) && (event_id != 0) && !"no".equals(optionmade)) {
                //an approval request was made
                Approve ap = new Approve();
                ap.setEventId(event_id);
                ap.setTo(user_id);
                ap.setReason(reason);
                ap.setFeedback(feedback);
                ap.setApproved("yes".equals(approve) ? true : false);
                ap.setRead(new Date(System.currentTimeMillis()));
                apdb.update(ap);
                apdb.setApproveActivity(ap.isApproved(), id);
                apdb.unifyApproveState(ap.isApproved(), event_id);

                //send alert to owner
                Event foralert = ar.createEvent(user_id, id,
                        Arbiter.PROJECT_TYPE, Event.ALERT);
                Alert alt = new Alert(foralert);
                alt.setAlertType(Alert.MESSAGE_ALERT);

                if (ap.isApproved())
                    alt.setPriority(Alert.PRIORITY_LOW);
                else
                    alt.setPriority(Alert.PRIORITY_HIGH);

                alt.setSent(new Date(System.currentTimeMillis()));

                //alt.setSourceObjId(id);
                //alt.setSourceType(Arbiter.PROJECT_TYPE);
                //alt.setSourceUserId(user_id);
                alt.setTo(actdb.getOwner(id));
                aldb.add(alt);

                if (ap.isApproved())
                    request.setAttribute("approved", new String());

                Utils.setBreadCrumbs(request, "bc.approval.changes");

                return mapping.findForward("approvalchanges");
            }

            //session refresh on lang change!
            SortedList approvals = (SortedList) session.getAttribute(Approve.LIST);

            if (approvals != null) {
                if ("name".equals(sort))
                    approvals.setComparator(new Approve.NameComparator());

                if ("type".equals(sort))
                    approvals.setComparator(new Approve.TypeComparator());

                if ("user".equals(sort))
                    approvals.setComparator(new Approve.UserNameComparator());

                if ("issuedate".equals(sort))
                    approvals.setComparator(new Approve.IssueDateComparator());

                if ("readdate".equals(sort))
                    approvals.setComparator(new Approve.ReadDateComparator());
            }

            if ( ((sshow == null) && (approvals == null)) || request.getParameter("start")==null) {
                approvals = apdb.getForUser(user.getId(), lang, Approve.ALL);
                session.setAttribute(Approve.LIST, approvals);
            }

            if (sshow != null ) {
                approvals = apdb.getForUser(user.getId(), lang,
                        Integer.parseInt(sshow));
                session.setAttribute(Approve.LIST, approvals);
            }

            //take out what we don't want to display:
            if (approvals.size() != 0) {
                if ("widget".equals(mode))
                    request.setAttribute("approvals", approvals);
                else {
                	 PageToken.tokenizeList( request,  sc,  approvals, "approvals");
                   /* List pagetk = PageToken.makePageTokens(approvals, token);
                    request.setAttribute("approvals",
                        PageToken.handleCurrent(request, sc, approvals));
                    request.setAttribute("pagetk", pagetk);*/
                }
            }

            if (blank)
                return mapping.findForward("empty");

            if (!"widget".equals(mode))
                Utils.setBreadCrumbs(request, "bc.approval.list");

            return "widget".equals(mode)
            ? mapping.findForward("approvalwidget")
            : mapping.findForward("listapprovals");
        } catch (Exception e) {
            BugTracker.publishBug(e, request);

            return mapping.findForward("fail");
        }
    }
}
